import React from 'react';
import {bindActionCreators} from 'redux';
import {
  Keyboard,
  Platform,
  ScrollView,
  StyleSheet,
  Text,
  View,
} from 'react-native';
import * as ActionCreator from '../../actions/order-form-actions';
import {connect} from 'react-redux';
import InputItem from '../../components/input-item';
import {formatDate, getRealSize} from '../../utils';
import PickerItem from '../../components/picker-item';
import Button from '../../components/button';
import Validator from 'async-validator';
import Toast from '../../components/toast';
import CheckBox from '../../components/check-box';
import {
  BottomSheetModal,
  BottomSheetModalProvider,
  BottomSheetView,
} from '@gorhom/bottom-sheet';
import SheetHead from '../../components/items/sheet-head';
import _ from 'lodash';
import ThemeStyles from '../../styles';
import {Calendar} from 'react-native-calendars';
import {I18n} from '../../reducers/intl';
import {connectActionSheet} from '@expo/react-native-action-sheet';

export const validator = new Validator({
  patientName: [
    {
      required: true,
      message: () => I18n.t('form.validate.message.patientName'),
    },
  ],
  patientGender: [
    {
      required: true,
      message: () => I18n.t('form.validate.message.patientGender'),
    },
    {
      type: 'enum',
      enum: ['male', 'female'],
      message: () => I18n.t('form.validate.message.patientGender'),
    },
  ],
  patientAge: [
    {
      required: true,
      message: () => I18n.t('form.validate.message.patientAge'),
    },
    {
      validator: (rule, value, callback) => {
        const age = Number(value);
        if (age > 0 && age < 120) {
          return callback();
        }
        callback(new Error(I18n.t('form.validate.message.patientAgeRate')));
      },
    },
  ],
  deliveryDay: [
    {
      required: true,
      message: () => I18n.t('form.validate.message.deliveryDay'),
    },
  ],
});

class PatientScreen extends React.PureComponent {
  static navigationOptions = () => ({
    headerBackTitleStyle: Platform.OS === 'ios' && {
      height: 0,
      width: 0,
    },
    title: I18n.t('page.title.create'),
  });

  onNext = async () => {
    const {navigation, form} = this.props;
    try {
      await validator.validate(form);
      navigation.navigate('OrderFormProduct');
    } catch (e) {
      Toast.show(e.errors[0].message);
    }
  };

  render() {
    const {
      form,
      orderFormActions,
      options,
      supplier,
      user,
      GenderOptions,
      minDate
    } = this.props;
    const dates = _.get(supplier, 'busy_dates', []);
    const markedDates = {};
    dates.forEach(item => {
      markedDates[item.date] = {
        selected: true,
        selectedColor: 'red',
        disabled: true,
        disableTouchEvent: true,
      };
    });

    const owners = user.owner_info || [];
    const associateOptions = owners.map(o => ({
      label: o.clinic_name || o.email,
      value: o.email,
    }));
    if (associateOptions.length) {
      associateOptions.push({
        label: I18n.t('button.cancel'),
        value: '',
      });
    }

    // <PickerItem
    //     isRequire
    //     placeholder={I18n.t('form.placeholder.gender')}
    //     value={form.patientGender}
    //     items={GenderOptions}
    //     onChange={value =>
    //         orderFormActions.updateForm({patientGender: value})
    //     }
    // />

    return (
      <BottomSheetModalProvider>
        <ScrollView style={Styles.container}>
          <View>
            <Text style={Styles.title}>{I18n.t('form.label.patient')}</Text>
            <View style={Styles.row}>
              <InputItem
                isRequire
                placeholder={I18n.t('form.placeholder.patientName')}
                value={form.patientName}
                onChange={value =>
                  orderFormActions.updateForm({patientName: value})
                }
              />
            </View>
            <View style={Styles.row}>
              <InputItem
                isRequire
                value={I18n.t(`options.gender.${form.patientGender}`)}
                onFocus={() => {
                  this.props.showActionSheetWithOptions(
                    {
                      options: GenderOptions.map(option => option.label),
                      cancelButtonIndex: 3,
                      destructiveButtonIndex: 3,
                      textStyle: {flex: 1},
                    },
                    buttonIndex => {
                      orderFormActions.updateForm({
                        patientGender: GenderOptions[buttonIndex].value,
                      });
                    },
                  );
                }}
                editable={false}
                onChange={value =>
                  orderFormActions.updateForm({patientAge: value})
                }
              />
            </View>
            <View style={Styles.row}>
              <InputItem
                isRequire
                value={form.patientAge}
                onFocus={() => {
                  this.BottomSheet.dismiss();
                }}
                placeholder={I18n.t('form.placeholder.age')}
                keyboardType="numeric"
                onChange={value =>
                  orderFormActions.updateForm({patientAge: value})
                }
              />
            </View>
            <View style={Styles.row}>
              <InputItem
                editable={false}
                isRequire
                value={form.deliveryDay}
                placeholder={I18n.t('form.placeholder.delivery')}
                onFocus={() => {
                  this.BottomSheet.present();
                  Keyboard.dismiss();
                }}
              />
            </View>
            <View style={Styles.row}>
              <InputItem
                isRequire
                placeholder={I18n.t('form.placeholder.owners')}
                value={form.owners}
                onFocus={() => {
                  if (!associateOptions.length) {
                    return;
                  }
                  this.props.showActionSheetWithOptions(
                    {
                      options: associateOptions.map(option => option.label),
                      cancelButtonIndex: associateOptions.length,
                      destructiveButtonIndex: associateOptions.length,
                      textStyle: {flex: 1},
                    },
                    buttonIndex => {
                      orderFormActions.updateForm({
                        owners: associateOptions[buttonIndex].value,
                      });
                    },
                  );
                }}
                editable={false}
                onChange={value => orderFormActions.updateForm({owners: value})}
              />
            </View>
          </View>
          <View>
            <Text style={Styles.title}>{I18n.t('form.label.patient')}</Text>
            <View style={Styles.row}>
              <CheckBox
                items={options}
                values={form.selections}
                onChange={values =>
                  orderFormActions.updateForm({selections: values})
                }
              />
            </View>
          </View>
          <View style={Styles.next}>
            <Button label={I18n.t('button.next')} onPress={this.onNext} />
          </View>
          <BottomSheetModal
            ref={ref => {
              this.BottomSheet = ref;
            }}
            style={Styles.sheetContainer}
            index={0}
            handleComponent={() => (
              <SheetHead onClose={() => this.BottomSheet.dismiss()} />
            )}
            snapPoints={[320]}>
            <BottomSheetView style={{flex: 1}}>
              <Calendar
                markedDates={markedDates}
                minDate={minDate}
                onDayPress={async day => {
                  orderFormActions.updateForm({deliveryDay: day.dateString});
                  this.BottomSheet.dismiss();
                }}
              />
            </BottomSheetView>
          </BottomSheetModal>
        </ScrollView>
      </BottomSheetModalProvider>
    );
  }
}

const mapStateToProps = state => ({
  appState: state.appState,
  user: state.user,
  form: state.orderForm,
  options: state.constant.selections,
  supplier: state.supplier,
  minDate: formatDate(),
  GenderOptions: [
    {
      label: I18n.t('options.gender.male'),
      value: 'male',
      key: 'male',
      inputLabel: I18n.t('options.gender.male'),
    },
    {
      label: I18n.t('options.gender.female'),
      value: 'female',
      key: 'female',
      inputLabel: I18n.t('options.gender.female'),
    },
  ],
});

const mapDispatchToProps = dispatch => ({
  orderFormActions: bindActionCreators(ActionCreator, dispatch),
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(connectActionSheet(PatientScreen));

const Styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: getRealSize(15),
  },
  title: {
    fontSize: getRealSize(22),
    fontWeight: 'bold',
    marginTop: getRealSize(18),
  },
  row: {
    marginTop: getRealSize(15),
    overflow: 'hidden',
  },
  next: {
    marginVertical: getRealSize(12),
    zIndex: -999,
  },
  sheetContainer: {
    borderTopColor: ThemeStyles.Color.line.color,
    borderTopWidth: StyleSheet.hairlineWidth,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 12,
    },
    shadowOpacity: 0.58,
    shadowRadius: 16.0,

    elevation: 24,
  },
});
